/**
 * Created by Administrator on 2017/1/18.
 */
var ActionAdd = {
    relevanceNum : 0,//关联券数量
    relevance:[],//关联券对象
    parkList :[],//停车场列表
    couponList:[],//优惠券列表
    parkId : "",//选中的停车场ID
    parkName : "",//选中停车场名称
    /**
     * 初始化页面
     */
    init:function () {
        var _t = this;
        //加载广场列表
        Common.Ajax.ajaxRequest({
            url: "/mgr/park/getParkList",
            type: "get",
            data: {}
        },function(data){
                _t.parkList = data.parkList;
                var optionHtml = "";
                //拼接下拉
                $.each(_t.parkList,function (i,item) {
                    optionHtml += `<option value='${item.id}'>${item.parkName}</option>`;
                })
                $("#parkId").append(optionHtml);
                $("select").comboSelect();
                //切换停车场查询该停车场优惠券，并且清空优惠券关联
                $("#parkId").on("change",function () {
                    _t.parkId = $("#parkId").val();
                    $("#parkName").val($("#parkId").find("option:selected").text());
                    _t.relevanceNum = 0;
                    _t.relevance = [];
                    $(".coupon-group").find("ul:gt(0)").empty();
                    _t.getCouponByParkId($("#parkId").val());
                })
            $("#type").on("change",function () {
                if($("#type").val() == 1){
                    $(".register").show();
                }else {
                    $(".register").hide();
                    $("#participant").val(0);
                    $("#partType").val(0);
                    $("#partNum").valid("");

                }
            });
        });
        //点击关联券
        $(".add-coupon").on("click",function () {
            var lenght = _t.couponList.length;//优惠券数量
            if(!_t.parkId){ alert("请选择活动广场");return}
            if(lenght === 0){ alert("活动广场下没有关联任何优惠券");return}
            if(_t.relevanceNum <= lenght-1){
                $(".coupon-group").append(_t.addCouponHtml());
                $(".delete").unbind().one("click",function (e) {
                    _t.removeCouponHtml(e)
                })
            }else{
                alert(`最多只能关联${lenght}条`);
            }
        });
        $("#cover").on("change",function(){
            var coverUrl = _t.getFileUrl("cover");
            var imgPre = document.getElementById("coverPre");
            imgPre.src = coverUrl;
            $("#coverPre").show();
        });
        $("#logo").on("change",function(){
            var logoUrl = _t.getFileUrl("logo");
            var imgPre = document.getElementById("logoPre");
            imgPre.src = logoUrl;
            $("#logoPre").show();
        });
        $("#backButton").on("click",function(){
            window.location.href = ctx + "/mgr/action/actionListView";
        });
    },
    //根据停车场id查询优惠券列表
    getCouponByParkId:function (parkId) {
        var _t = this;
        Common.Ajax.ajaxRequest({
            url: "/mgr/coupon/selectCouponById",
            type: "get",
            data: {parkId: parkId}
        },function(data){
            _t.couponList = data.couponList;
        })
    },
    setOption:function (id) {
        var _t = this,couponHtml='';
        $.each(_t.couponList,function (i,obj) {
            if(obj.id && obj.id == id){
                couponHtml += `<option value="${obj.id}" selected>${obj.couponName}</option>`;
            }else{
                couponHtml += `<option value="${obj.id}">${obj.couponName}</option>`;
            }
        })
        return couponHtml;
    },
    addCouponHtml:function () {
        return `<ul>
                    <li class="col-sm-3">
                        <div>${++this.relevanceNum}</div>
                    </li>
                    <li class="col-sm-4">
                        <select class='form-control' name="couponId">
                           ${this.setOption()}
                        </select>
                    </li>
                    <li class="col-sm-3">
                        <input class="form-control" name="couponNum" type="text" />
                    </li>
                    <li class="col-sm-2 delete">
                        <i class="fa fa-times red" aria-hidden="true"></i>
                    </li>
                </ul>`;
    },
    refreshCouponHtml : function () {
        var _t = this;
        $(".coupon-group").empty();
        var couponHtml = `  <ul>
                                <li class="col-sm-3">
                                    <div>序号</div>
                                </li>
                                <li class="col-sm-4">
                                    <div>券名称</div>
                                </li>
                                <li class="col-sm-3">
                                    <div>发券数量</div>
                                </li>
                            </ul>`;
        $.each(_t.relevance,function (i,obj) {
            couponHtml +=  `<ul>
                                <li class="col-sm-3">
                                    <div>${++_t.relevanceNum}</div>
                                </li>
                                <li class="col-sm-4">
                                    <select class='form-control' name="couponId">
                                        ${_t.setOption(obj.couponId)}
                                    </select>
                                </li>
                                <li class="col-sm-3">
                                    <input class="form-control" name="couponNum" value="${obj.couponNum}" type="text" />
                                </li>
                                <li class="col-sm-2 delete">
                                    <i class="fa fa-times red" aria-hidden="true"></i>
                                </li>
                            </ul>`;
        })
        $(".coupon-group").append(couponHtml);
        _t.relevance = [];
        $(".delete").unbind().one("click",function (e) {
            _t.removeCouponHtml(e)
        })
    },
    removeCouponHtml : function (e) {
        var _t = this;
        _t.relevanceNum = 0;
        $(e.currentTarget).parent().remove();
        $(".coupon-group").find("ul").each(function (index,item) {
            if(index === 0) {
                return;
            }
            var obj = {};
            obj.couponId = $($(item).find('li')[1]).find("select").val();
            obj.couponNum =  $($(item).find('li')[2]).find("input").val();
            _t.relevance.push(obj);
        })
        _t.refreshCouponHtml();
    },
    submit:function () {
    var formData = new FormData($( "#addForm" )[0]);
        $.ajax({
            url: ctx + "/mgr/action/addAction",
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                toastr.info("新增活动成功");
                window.location.href = ctx + "/mgr/action/actionListView";
            },
            error: function (data) {
                toastr.error("添加失败");
            }
        });
    },
    /**
     * 从 file 域获取 本地图片 url
     */
    getFileUrl:function(sourceId) {

        var url;
        if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
            url = document.getElementById(sourceId).value;
        } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
            url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
        } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
            url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
        }
        return url;
    }
}
    $(document).ready(function () {
        ActionAdd.init();
        $("#addForm").validate({
            focusCleanup: true,
            focusInvalid: false,
            onkeyup: true,
            rules: {
                parkId: {
                    required: true
                }, actionName: {
                    required: true
                }, type: {
                    required: true
                }, startDate: {
                    required: true
                }, endDate: {
                    required: true,
                }, cover: {
                    required: true
                }, logo: {
                    required: true
                }
            },
            messages: {
                couponName: {
                    required: "请选择停车场"
                }, amount: {
                    required: "活动名称不能为空"
                }, total: {
                    required: "请选择活动类型"
                }, startTime: {
                    required: "请选择活动开始时间"
                }, endTime: {
                    required: "请选择活动结束时间"
                }, cover: {
                    required: "请上传活动封面"
                }, logo: {
                    required: "请上传活动logo"
                }
            },
            submitHandler: ActionAdd.submit
        });
})